package alipay.openplatform.edu.campus.jiuye.common.utils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

/**
 * 序列化及反序列化工具类
 * Created by gongzhijie on 16/8/26.
 */
public class SerializeUtil {
    /**
     * 序列化
     *
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 反序列化
     *
     * @param bytes
     * @return
     */
    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 将request输入流转换成字符串
     * controller接收json格式数据
     * @param request
     * @return
     */
    public static String requestToString(HttpServletRequest request) {
        if(request == null) return null;

        InputStream in = null;
        StringBuilder sb = new StringBuilder();
        try {
            in = request.getInputStream();
            if (in == null) {
                return null ;
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace() ;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return sb.toString();
    }
}
